<template>
  <div class="monitoring">
    <header>
      <div class="left">
        <div class="search">
          <div class="chunk">
            <el-input placeholder="主数据名称" v-model="searchForm.mdmName"
                      @keyup.enter.native="submitsearchForm">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="submitsearchForm"></i>
            </el-input>
          </div>
          <div class="chunk">
            <el-select v-model="searchForm.mdmType" placeholder="主数据类型" clearable @change="submitsearchForm">
              <el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="right">
        <el-button type="primary" icon="el-icon-plus" @click="addApp">新增</el-button>
      </div>
    </header>
    <main>
      <BaseTable ref="mainTable" :tableData="tableData" :tableColumn="tableColumn" :funData="funData"
                 :funWidth="funWidth" :showIndex="true" :tabLoading="mainTabLoading" @onFunc="tableButtonHandle"
                 :tableHeight="'70vh'" :border="false">
        <template v-slot:mdmName="{ row }">
          <div class="nameCard" style="margin: 0 auto">
            <div class="image" v-loading="row.imgLoading">
              <template v-if="row.imgUrl">
                <img :src="row.imgUrl" alt=""/>
              </template>
              <template v-else>
                <img src="./images/icon.png">
              </template>
            </div>
            <div class="nameInfo">
              <div class="name">{{ row.mdmName }}</div>
            </div>
          </div>
        </template>
        <template v-slot:accessMode="{ row }">
          <div class="taskClasses">
            <span :class="`state${item}`" v-for="(item,index) in JSON.parse(row.accessMode)"
                  :key="index">{{ methods_dist[item] }}</span>
          </div>
        </template>
        <template v-slot:interfaceStatus="{ row }">
          <el-switch active-value="1" inactive-value="2" active-color="#60c958" v-model="row.interfaceStatus"
                     disabled></el-switch>
        </template>
        <template v-slot:dbStatus="{ row }">
          <el-switch active-value="1" inactive-value="2" active-color="#60c958" v-model="row.dbStatus"
                     disabled></el-switch>
        </template>
        <template v-slot:appStatus="{ row }">
          <el-switch active-value="1" inactive-value="2" active-color="#60c958" v-model="row.appStatus"
                     @change="(val)=>appStatusChange(val,row)"></el-switch>
        </template>
      </BaseTable>
    </main>
    <footer>
      <basePage :pageModel="pageModel" @update:pageModel="currentChangeHandle"></basePage>
    </footer>
  </div>
</template>
<script>
import configData from "./configData.js";
import dayjs from "dayjs";
import BaseTable from "@/views/intergrationTask/compoments/baseTable.vue";
import basePage from "@/views/intergrationTask/compoments/basePage.vue";
import {getApiModuleApi} from "@/api/apiChunks/index.js";
import {downloadLogo} from "@/api/apis/logo.js";
import request from "@/utils/request";

export default {
  name: "listOfApps",
  data() {
    return {
      refreshLoading: false,
      searchForm: {
        task_name: "",
      },
      imgLoading:false,
      mainTabLoading: false,
      funData: [
        {
          type: "setting",
          text: "设置",
          color: "#5a9cf8",
        },
      ],
      tableColumn: configData.tableColumn,
      tableData: [],
      imgUrl: "",
      pageModel: {
        pageIndex: 1,
        total: 10,
        limit: 10,
      },
      classOptions: [],
      stateOptions: [
        {
          label: "启用",
          value: "1",
        },
        {
          label: "停用",
          value: "2",
        },
      ],
      methods_dist: {
        1: "接口",
        2: "H5",
        3: "PC网页",
        4: "PC应用程序",
      },
    };
  },
  methods: {
    // 状态改变
    async appStatusChange(val, row) {
      const res = await getApiModuleApi({
        tl: "sysApplicationService",
        as: "application",
        dj: "enableOrDisableApp"
      }, {id: row.id, appStatus: val})
      this.$vmNews(res.msg, 'success')
    },
    async initSelectOptions() {
      let params = {
        tab_name: "mdm",
        column_name: "mdm_type",
      };
      const res = await getApiModuleApi({
        tl: "generalServiceImpl",
        as: "dictionaryshop",
        dj: "selectDictionaryshop"
      }, params)
      this.classOptions = [];
      res.attribute.forEach((item) => {
        this.classOptions.push({
          label: item.column_content,
          value: item.column_value
        })
      })
    },
    // 添加应用
    addApp() {
      this.$router.push({
        path: "/integrationOption/masterDataAdd",
        query: {flag: "add"},
      });
    },
    // 时间处理
    getTimeHandler(time) {
      var days = parseInt(time / (1000 * 60 * 60 * 24));
      var hours = parseInt((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = parseInt((time % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = (time % (1000 * 60)) / 1000;
      return days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
    },
    // 初始化表单
    async initMainTableData(obj = {}) {
      this.refreshLoading = true;
      const res = await getApiModuleApi(
          {
            tl: "mdmService",
            as: "mdmService",
            dj: "queryMdmPage",
          },
          {
            pageNum: this.pageModel.pageIndex,
            pageSize: this.pageModel.limit,
            ...obj,
          }
      );
      this.refreshLoading = false;
      if (res.status == 200) {
        this.pageModel.total = res.attribute.total;
        this.imgLoading = true
        res.attribute.list.map(el => {
          this.$set(el,'imgLoading',true)
          return request({
            url: "/kangarooDataCenter/entranceController/fileDownloadNew?id=" + el.mdmLogo,
            method: "get",
            responseType: 'arraybuffer'
          }).then((res) => {
            el.imgLoading = false
            if(!res.byteLength) return
            let tempImgUrl =
                "data:image/png/jpg;base64," + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ""));
            this.$set(el, 'imgUrl', tempImgUrl)
          })
        })
        this.tableData = res.attribute.list;
      }
    },
    //下载头像
    async getImageUrl(id) {
      // const res = await downloadLogo(id);
      // const blob = new Blob([res]);
      // return URL.createObjectURL(blob);
      // this.imgUrl = URL.createObjectURL(blob)

    },
    // 点击提交
    submitsearchForm() {
      this.initMainTableData(this.searchForm);
    },
    // 表单操作
    tableButtonHandle(val, item) {
      if (item.type === "setting") {
        this.$router.push({
          path: "/integrationOption/settingMenu/masterDataEdit",
          query: {flag: "setting", id: val.id, name: val.name, appLogo: val.appLogo},
        });
      } else if (item.type === "copy") {
        this.$router.push({
          path: "/applicationList/applicationAdd/masterDataEdit",
          query: {flag: "copy", id: val.id, appLogo: val.appLogo},
        });
      }
    },
    // 页码
    currentChangeHandle(pageModel) {
      this.pageModel = pageModel;
      this.$nextTick(() => {
        this.initMainTableData(this.searchForm);
      });
    },
  },
  computed: {
    // 操作框的宽度
    funWidth() {
      return this.funData.length * 70;
    },
  },
  components: {
    BaseTable,
    basePage,
  },
  created() {
    // this.initMainTableData();
    this.initSelectOptions()
  },
  activated() {
    this.initMainTableData(this.searchForm);
  },
  beforeRouteLeave(to, from, next) {
    if (!to.path.includes("applicationList")
    ) {
      next();
      this.$destroy("listOfApps");
    } else {
      next();
    }
  },
};
</script>

<style scoped lang='scss'>
::v-deep .el-button {
  border-radius: 16px;
}
.monitoring {
  position: relative;
  width: 100%;
  overflow: auto;

  header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background-color: #fff;
    border-radius: 20px;

    .left {
      align-items: center;
      display: flex;

      .search {
        margin-left: 30px;
        display: flex;

        > .chunk {
          margin-left: 10px;
        }
      }
    }
  }

  main {
    margin-top: 10px;
    padding: 20px 20px 5px;
    height: 75vh;
    border-radius: 20px;
    background-color: #fff;
  }

  footer {
    margin-top: 20px;
  }

  .nameCard {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    .image {
      width: 29px;
      height: 29px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .nameInfo {
      margin-left: 5px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;

      > .name {
        text-align: left;
        font-size: 14px;
        font-weight: 600;
      }

      > .version {
        margin-top: 1px;
        color: #ff8b0f;
        font-size: 12px;
        height: 20px;
        border: 0.5px solid #ff8b0f;
        padding: 0 1px;
      }
    }
  }
}

.taskClasses {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;

  span {
    margin-top: 5px;
    border-radius: 2px;
    padding: 2px 10px;
    margin-left: 8px;
    color: #fff;
  }

  .state1 {
    background-color: #1478f6;
  }

  .state2 {
    background-color: #f64114;
  }

  .state3 {
    background-color: #00bd72;
  }

  .state4 {
    background-color: #b700bd;
  }
}
</style>
